<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col>

        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" size="small" clearable style="width: 150px"/>
          </el-form-item>
          <el-form-item label="项目状态" prop="statusCode">
            <el-select @change="handleQuery" v-model="queryParams.statusCode" size="small" clearable style="width: 150px" placeholder="请选择">
              <el-option key="" label="全部" value=""/>
            </el-select>
          </el-form-item>
          <el-form-item label="更新时间">
            <el-date-picker @change="handleQuery" v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary"  size="mini" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery('queryForm')">重置</el-button>
          </el-form-item>
        </el-form>
      <div class="project-grid-container">
        <div class="project-grid-view">
            <!--beg-->
          <div  v-hasPermi="['saveFormProject']"class="project-template-view" style="display: flex; align-items: center;" @click="handleAdd">
            <div style="flex: 1;">
              <i class="el-icon-plus" style="font-size: 40px; align-items: center;" />
              <p style="font-size: 14px;color: #4aa71c">创建一个新问卷项目</p>
            </div>
          </div>

          <div v-for="item in dataList" :key="item.projectId" class="project-template-view">
            <img :src="item.coverImg" style="width: 100%; height: 133px;" @click="toProjectBrowseHandle(item,'editor')" >
            <p class="project-template-title" @click="toProjectBrowseHandle(item,'editor')" >
              {{ item.projectName }}
            </p>
            <p style="color: rgba(189, 188, 188, 100); font-size: 12px; margin: 0;">
              <span :style="'color:'+item.statusColor">{{ item.updateTime }} [{{ item.statusName }}]</span>
            </p>

            <div class="project-template-use-view">
              <div class="project-template-use-view-btn" >
                <el-button  icon="el-icon-setting" type="text" v-hasPermi="['updateFormProject']"   @click="toProjectHandle(item.projectId,'editor')"  >设计</el-button>
                <el-button  icon="el-icon-edit" type="text" v-hasPermi="['updateFormProject']"   @click="handleUpdate(item)" >编辑</el-button>
                <el-button icon="el-icon-s-data"  v-if="item.statusCode==='FORM_PROJECT_PUBLISHED'" type="text" @click="toProjectStatisticsHandle(item.projectId)" >统计</el-button>
                <el-button v-hasPermi="['deleteFormProject']"   v-if="item.statusCode==='FORM_PROJECT_UNPUBLISHED'" icon="el-icon-delete" type="text" @click="handleDelete(item)" >删除</el-button>
              </div>
            </div>
          </div>
           <!-- end-->
        </div>
      </div>
        <div>
          <pagination v-show="total>0" layout="prev, pager, next" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows" @pagination="queryFormProjectPageResList"/>
        </div>
      </el-col>
    </el-row>
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="addUpdateOpen" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="addUpdateOpenRules"  label-width="80px">

        <el-form-item label="项目名称" prop="projectName">
          <el-input :hide-required-asterisk="true" autocomplete="off" v-model="form.projectName" placeholder="请输入项目名称,50个字符长度" maxlength="50" />
        </el-form-item>

        <el-form-item label="项目封面" prop="coverImg" ref="coverImg">
          <el-upload
            ref="image"
            class="avatar-uploader"
            action="#"
            :auto-upload="false"
            accept="image/jpeg,image/gif,image/png,image/jpg"
            :on-change="requestUpload"
            :show-file-list="false">
          <img v-if="form.coverImg" :src="form.coverImg"  class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <!--   <el-form-item label="备注说明" prop="remark">
             <el-input :hide-required-asterisk="true" autocomplete="off" v-model="form.remark" placeholder="请输入备注说明" maxlength="255" />
           </el-form-item>-->

        <el-form-item label="排序" prop="sort">
          <el-input-number :hide-required-asterisk="true" v-model="form.sort" :min="1" :max="10000" label="排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelAddUpdateOpen">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 数据统计对话框 -->
    <el-dialog title="数据统计" center :visible.sync="statisticsOpen"   :fullscreen=true append-to-body>
      <div class="statistics-tabs">
        <el-tabs v-model="activeName" type="border-card">
          <el-tab-pane label="列表视图" name="list">
            <list :key="projectId" :pId="projectId"/>
          </el-tab-pane>
          <el-tab-pane label="统计视图" name="chart">
            <chart :key="projectId" :pId="projectId"/>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </div>
</template>


<script>
  import list from '../statistics/list'
  import chart from '../statistics/chart'
  import {queryFormProjectPageResList, saveFormProject, updateFormProject, deleteFormProjectByProjectId} from '@/api/form/formProject'
  //默认查询参数
  let defaultQueryParams = {
    projectName: undefined,
    startTime: undefined,
    endTime: undefined,
    statusCode: "",
    projectTypeCode: undefined,
    remark: undefined,
    page: 1,
    rows: 9
  }
  export default {
    name: 'formProjectAdmin',
    components: {
      list,
      chart
    },
    data() {
      return {
        //项目id
        projectId: null,
        //统计弹窗
        statisticsOpen:false,
        //默认定位
        activeName: 'list',
        // 显示搜索条件
        showSearch: true,
        // 日期范围
        dateRange: [],
        // 查询参数
        queryParams: { ...defaultQueryParams },
        //总条数
        total: 0,
        //数据内容
        dataList: [],
        // 弹出层标题
        title: "",
        // 是否显示新增修改弹出层
        addUpdateOpen: false,
        // 表单项目状态
        statusOptions: [],
        // 增加修改表单参数
        form: {},
        // 新增修改表单校验
        addUpdateOpenRules: {
          projectName: [
            { required: true, message: "项目名称不能为空",trigger: "blur" },
          ],
          coverImg: [
            { required: true, message: "封面图片必须上传"},
          ],
          sort: [
            { required: true, message: "排序不能为空"},
          ]
        }
      }
    },
    computed: {},
    created() {
      this.queryFormProjectPageResList()
    },
    methods: {
      //跳转到项目
      toProjectHandle(key, type) {
        this.$router.push({path: `/project/form/${type}`, query: {key: key, active: type}})
      },

      //跳转到项目统计分析界面
      toProjectStatisticsHandle(key, type) {
        this.statisticsOpen = true;
        this.projectId = key;
        //this.$router.push({path: `/project/${type}`, query: {key: key, active: type}})
      },

      //跳转到浏览界面
      toProjectBrowseHandle(item) {
        if (item.statusCode!=='FORM_PROJECT_PUBLISHED'){
          this.toProjectHandle(item.projectId,'editor');
        }else {
          let url = window.location.protocol + '//' + window.location.host
          let writeLink = `${url}#/m/${item.projectId}`
          window.open(writeLink, "_blank");
        }
      },
      //上传封面图
      requestUpload(file) {
       let that = this
        const typeArr = ['image/png', 'image/gif', 'image/jpeg', 'image/jpg'];
        const isJPG = typeArr.indexOf(file.raw.type) !== -1;
        if (!isJPG) {
          this.$message.error('只能是图片!');
          return;
        }
        const isLt1M = file.size / 1024 / 1024 < 1;
        if (!isLt1M) {
          this.$message.error('上传项目图片大小不能超过 1M!');
          return
        }
        let reader = new FileReader();
        reader.readAsDataURL(file.raw);
        reader.onload = function(e){
          that.form = {
            ...that.form,
            coverImg: this.result
          }
          that.$refs["coverImg"].clearValidate()
          //console.log(file.name);
          //console.log(this.result)//图片的base64数据
        }
      },
      /** 查询表单项目列表 */
      queryFormProjectPageResList() {
        queryFormProjectPageResList(this.addDateRange(this.queryParams, this.dateRange)).then(res => {
          this.dataList = res.data.records
          this.total = res.data.total
          }
        )
      },

      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.addUpdateOpen = true;
        this.title = "添加问卷项目";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        //修改表单填充
        this.form = {...row};
        this.addUpdateOpen = true;
        this.title = "修改问卷项目";
      },

      /** 删除按钮操作 */
      handleDelete(row) {
        this.$confirm('是否确认删除所选问卷项目?', "警告", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        }).then(function() {
          const projectId={projectId:row.projectId}
          return deleteFormProjectByProjectId(projectId);
        }).then(response => {
          this.$modal.msgSuccess(response.message)
          this.queryFormProjectPageResList();
        }).catch(function() {});
      },

      /** 重置按钮操作 */
      resetQuery(fromId) {
        this.dateRange = []
        this.resetForm(fromId)
        this.handleQuery()
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1
        this.queryFormProjectPageResList()
      },
      /** 提交保存或修改按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.projectId !== undefined) {
              updateFormProject(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.queryFormProjectPageResList();
                this.addUpdateOpen = false
              });
            } else {
              saveFormProject(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                //this.queryFormProjectPageResList();
                this.addUpdateOpen = false
                this.toProjectHandle(response.data,'editor')
              });
            }
          }
        });
      },
      // 取消修改增加弹出层按钮
      cancelAddUpdateOpen() {
        this.addUpdateOpen = false
      },
      // 表单重置
      reset() {
        this.form = {
          projectId: undefined,
          projectName: undefined,
          sort: 1,
          remark: undefined
        };
        this.resetForm('form')
      }

    }
  }
</script>

<style lang="less" scoped>
  .project-grid-container{
    width: 100%;
    margin: auto 0;
    text-align: center;
  }
  .project-grid-view {
    display: flex;
    width: 1450px;
    text-align: center;
    margin:0 auto;
    flex-direction: row;  /*横向*/
    align-items: center; /*纵轴居中*/
    flex-wrap: wrap;
    clear: both;
  }
  .project-template-view {
    height: 215px;
    width: 250px;
    line-height: 20px;
    border-radius: 3px;
    text-align: center;
    margin: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
    background: white;
  }

  .wan-row-justify-box {
    flex-direction: row;
    flex-wrap: wrap;
  }


  @media screen and (min-width: 1200px) {
    .el-col-md-6 {
      width: 20%;
    }
  }


  .project-template-view:hover .project-template-use-view {
    display: block;
    cursor: pointer;
  }

  .project-template-use-view {
    width: 100%;
    height: 28px;
    z-index: 100;
    background-color: #f0f0f0;
    filter: alpha(opacity=60);
    -moz-opacity: 0.6;
    opacity: 0.6;
    display: none;
    border: none;
  }

  .project-template-title {
    color: rgba(16, 16, 16, 100);
    font-size: 14px;
    margin: 0 3px;
    line-height: 30px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    line-height: 178px;
    display: block;
  }
</style>
